package permission

import (
	"encoding/json"
	"net/http"
	"strings"

	"easy-sys/config"
	"easy-sys/sys/domain/user"
	"easy-sys/utils"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

// RouterHasPermission 权限中间件， 控制需要什么权限才可以继续执行
func RouterHasPermission(auth string) gin.HandlerFunc {
	return func(c *gin.Context) {
		session1 := sessions.Default(c)
		if session1.Get("userInfo") != nil {
			p := &user.SysUser{}
			json.Unmarshal([]byte(session1.Get("userInfo").(string)), p)
			if !checkDemoAllow(auth, p.Name) {
				c.JSON(http.StatusOK, utils.GetFailureMessage("Demo演示环境这次请求还是算了吧"))
				c.Abort()
				return
			}
			for i := 0; i < len(p.Permissions); i++ {
				if auth == p.Permissions[i] {
					return
				}
			}
			c.JSON(http.StatusOK, utils.GetFailureMessage("需要权限:"+auth+",无权限访问"))
			c.Abort()
			return
		} else {
			c.JSON(http.StatusOK, utils.GetFailureMessage("无法获取登录信息,无权限访问"))
			c.Abort()
			return
		}
	}
}

// checkDemoAllow 检查是否可以在演示环境下允许请求
func checkDemoAllow(auth string, userName string) bool {
	var isAllow = true
	if config.Cfg.Sys.Demo && userName != config.Cfg.Sys.DemoSuperUser {
		for _, value := range config.Cfg.Sys.DemoNotAllowAuthArr {
			if strings.Contains(auth, value) {
				isAllow = false
			}
		}
	}
	return isAllow
}
